import 'dart:async';

import 'package:core_package/core_package.dart';
import 'package:core_package/share/size_fill.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/request/promotion_request.dart';
import 'package:flutter_app_unionad/router/routes.dart';
import 'package:flutter_app_unionad/view_model/page_manager_view_model.dart';
import 'package:flutter_unionad/flutter_unionad.dart' as FlutterUnionad;

class SplashViewPage extends StatefulWidget {
  @override
  _SplashViewPageState createState() => _SplashViewPageState();
}

class _SplashViewPageState extends State<SplashViewPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (Configuration.promotionList != null && Configuration.promotionList!.length != 0) {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        if (count == 0) {
          PagesManagerViewModel.splashUpdateType(context);
        } else {
          if (mounted) setState(() {});
        }
        count--;
      });
    }
  }

  Timer? _timer;

  int count = 5;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        body: buildContent(context),
      ),
    );
  }

  Widget buildContent(context) {
    if (Configuration.promotionList == null || Configuration.promotionList!.length == 0) {
      return buildAD();
    }
    return buildImage();
  }

  Widget buildImage() {
    return Stack(
      children: [
        Center(
          child: GestureDetector(
            onTap: () {
              _timer?.cancel();
              PagesManagerViewModel.splashUpdateType(context);
              if (Configuration.promotionList![0].link != null) {
                gotoApp(context, route: Configuration.promotionList![0].link!, isSplash: false);
              } else {
                gotoApp(context, route: 'nnapp:///sharePage', isSplash: false);
              }
            },
            child: ShowPicWidget(
              Configuration.promotionList![0].coverImg ?? '',
              radius: 0,
              width: SizeFill.screenWidth!,
              height: SizeFill.screenHeight,
              fit: BoxFit.cover,
              showDefault: false,
            ),
          ),
        ),
        Positioned(
          top: SizeFill.statusHeight! + 10.px,
          right: 20,
          child: GestureDetector(
            onTap: () {
              _timer?.cancel();
              PagesManagerViewModel.splashUpdateType(context);
            },
            child: Container(
              alignment: Alignment.center,
              height: 20.px,
              decoration: BoxDecoration(
                color: Colors.black38,
                borderRadius: BorderRadius.circular(20.px),
              ),
              padding: EdgeInsets.symmetric(horizontal: 10.px),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    '${count}s',
                    style: TextStyle(
                      color: MyColors.color_255_145_17,
                      fontSize: 12.px,
                    ),
                  ),
                  Text(
                    '|跳过',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.px,
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  bool _offstage = true;

  Widget buildAD() {
    FlutterUnionad.FlutterUnionad.getSDKVersion().then((value) {
      print("fff ---- $value");
    });
    print('SizeFill.screenWidth${SizeFill.screenWidth},  SizeFill.screenHeight${SizeFill.screenHeight}');
    return Offstage(
      offstage: _offstage,
      child: Container(
        child: FlutterUnionad.FlutterUnionad.splashAdView(
          androidCodeId: "887759718",
          mIsExpress: true,
          //android 开屏广告广告id 必填
          iosCodeId: "887302981",
          //ios 开屏广告广告id 必填
          supportDeepLink: true,
          //是否支持 DeepLink 选填
          expressViewWidth: SizeFill.screenWidth!,
          // 期望view 宽度 dp 必填
          expressViewHeight: SizeFill.screenHeight,
          //期望view高度 dp 必填
          downloadType: FlutterUnionad.FlutterUnionadDownLoadType.DOWNLOAD_TYPE_POPUP,
          callBack: FlutterUnionad.FlutterUnionadSplashCallBack(
            onClick: () {
              print('onClick');

              PagesManagerViewModel.splashUpdateType(context);
            },
            onShow: () {
              print('onShow');
              setState(() => _offstage = false);

              // PagesManagerViewModel.splashUpdateType(context);
            },
            onFail: (message) {
              print('onFail');

              // Navigator.pop(context);
              PagesManagerViewModel.splashUpdateType(context);
            },
            onFinish: () {
              print('onFinish');

              PagesManagerViewModel.splashUpdateType(context);
            },
            onTimeOut: () {
              print('onTimeOut');

              PagesManagerViewModel.splashUpdateType(context);
            },
            onSkip: () {
              print('onSkip');

              // Navigator.pop(context);
              PagesManagerViewModel.splashUpdateType(context);
            },
          ),
        ),
      ),
    );
  }

  int last = 0;

  Future<bool> _onWillPop() {
    int now = DateTime.now().millisecondsSinceEpoch;
    if (now - last > 8000) {
      last = DateTime.now().millisecondsSinceEpoch;
      ShowToastWidget.showToast(msg: "再次点击返回退出应用", gravity: ToastGravity.BOTTOM);
      return Future.value(false);
    } else {
      return Future.value(true);
    }
  }
}
